<template>
  <a-drawer
    title="待处理账单明细"
    :maskClosable="true"
    :visible="visible"
    :width="1200"
    @close="closeModal"
    :destroyOnClose="true"
  >
    <a-row type="flex" style="background: #eee; padding: 10px 20px;">
      <a-col :span="4" v-if="detail.collectionCount">
        <a-statistic title="待收款账单数" :value="detail.collectionCount"/>
      </a-col>
      <a-col :span="5" v-if="detail.collectionAmount">
        <a-statistic title="待收款金额" :value="`￥${detail.collectionAmount}`"/>
      </a-col>
      <a-col :span="4" v-if="detail.paymentCount">
        <a-statistic title="待付款账单数" :value="detail.paymentCount"/>
      </a-col>
      <a-col :span="5" v-if="detail.paymentAmount">
        <a-statistic title="待付款金额" :value="`￥${detail.paymentAmount}`"/>
      </a-col>
      <a-col :flex="1">
        <div class="action-box">
          <a-space>
            <a-button v-if="detail.collectionCount" type="primary" ghost @click="handleAdd('INCOME', Number(detail.collectionAmount))">
              添加收款流水
              <text-tip
                :tips="['创建的流水默认发生额为待处理收款账单总金额，创建后需手动匹配对应账单。']"
              />
            </a-button>
            <a-button v-if="detail.paymentCount" type="primary" ghost @click="handleAdd('PAY', Number(detail.paymentAmount))">
              添加付款流水
              <text-tip
                :tips="['创建的流水默认发生额为待处理付款账单总金额，创建后需手动匹配对应账单。']"
              />
            </a-button>
          </a-space>
        </div>
      </a-col>
    </a-row>
    <div class="mt-10" >
      <a-table
        :dataSource="dataSource"
        :columns="INIT_COLUMNS"
        :pagination="false"
        rowKey="bill_id"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'bill_number'">
            <a-button type="link" @click="onBillClick(record)">{{
                text
              }}</a-button>
          </template>
          <template v-if="column.key === 'carry_over'">
            <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
            <span v-if="record.out_amount">
                     <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
            <span v-if="record.into_amount || record.out_amount" style="margin-left: 4px; font-size: 12px" class="link" @click="viewCarryOver(record)">
                    查看
                  </span>
          </template>
          <template v-if="column.key === 'confiscations_amount'">
            <span>{{text || '--'}}</span>
            <span v-if="text > 0" class="link" style="margin-left: 6px" @click="viewForfeit(record)">
              查看记录
            </span>
          </template>
          <template v-if="column.key === 'actual_retreat'">
            <a-tag color="red" v-if="record.bill_type == 2 || record.settle_status == 4">付</a-tag>
            <a-tag color="green" v-else>收</a-tag>
            <span>{{text || '--'}}</span>
          </template>
        </template>
      </a-table>
    </div>


    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="billId"
      @cancel="handleCancelDetail"
    />

    <!--  结转明细  -->
    <CarryOverMoreDetail
      :visible="carryDetailVisible"
      :id="billId"
      @handleCancel="handleCancelDetail"
    />

    <!--  罚没记录  -->
    <ForfeitRecordDrawer
      viewType="view"
      :visible="forfeitRecordVisible"
      :contractId="id"
      :billId="billId"
      @handleClose="forfeitRecordVisible = false"
    />

    <!--  添加收支流水  -->
    <AddBillTurnoverDrawer
      :visible="addBillTurnoverVisible"
      :defaultLoanType="addTurnoverType"
      :defaultAmount="addTurnoverAmount"
      :ownerId="detail.owner_id"
      @handleClose="handleAddTurnoverClose"
      @handleSuccess="saveAddTurnover"
    />
  </a-drawer>
</template>

<script>
import {defineComponent, watch, reactive, toRefs, computed, ref, defineAsyncComponent} from "vue";
import store from "../../../../store";
import moment from "moment";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
import CarryOverMoreDetail from "@/views/bill/NewRetreat/modules/CarryOverMoreDetail.vue";
import ForfeitRecordDrawer from "@/views/bill/NewRetreat/modules/ForfeitRecordDrawer.vue";
const BillDetailDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);
const AddBillTurnoverDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillTurnover/modules/AddBillTurnoverDrawer.vue")
);
import { TextTip } from "bl-common-vue3";
export default defineComponent({
  name: "PendingBillDrawer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,  // 合同id
    },
  },
  components: {
    ForfeitRecordDrawer,
    CarryOverMoreDetail,
    BillDetailDrawer,
    AddBillTurnoverDrawer,
    TextTip,
  },
  setup(props, {emit}) {


    const closeModal = () => {
      emit("handleCancel");
    };


    const state = reactive({
      dataSource: [],
      billId: 0,
      billDetailVisible: false,
      carryDetailVisible: false,
      forfeitRecordVisible: false,
      detail: {},
      addBillTurnoverVisible: false,
      addTurnoverType: '',
      addTurnoverAmount: 0,
    });

    const getDetail = () => {
      request.get('/org', "/bill/viewOnHandleBill", {contract_id: props.id}).then((res) => {
        state.detail = res?.list || {};
        state.dataSource = res?.list?.list || [];
      })
    };

    const onBillClick = (record) => {
      state.billId = record?.bill_id;
      state.billDetailVisible = true;
    };

    const handleAdd = (type, amount) => {
      state.addTurnoverType = type;
      state.addTurnoverAmount = amount;
      state.addBillTurnoverVisible = true;
    };

    /* 查看结转明细 */
    const viewCarryOver = (record) => {
      state.billId = record.bill_id;
      if (!state.billId) return;
      state.carryDetailVisible = true;
    };

    /* 查看罚没明细 */
    const viewForfeit = (record) => {
      state.billId = record.bill_id;
      if (!state.billId) return;
      state.forfeitRecordVisible = true;
    };

    const init = () => {
      getDetail();
    };

    const handleCancelDetail = () => {
      state.billDetailVisible = false;
      state.carryDetailVisible = false;
      init();
    };

    const handleAddTurnoverClose = () => {
      state.addBillTurnoverVisible = false;
    };

    const saveAddTurnover = () => {
      handleAddTurnoverClose();
      init();
    };

    const reset = () => {
      state.dataSource = [];
    };

    watch(
      () => props.visible,
      (visible) => {
        if (visible) {
          init();
        } else {
          reset();
        }
      }
    );
    return {
      ...toRefs(state),
      INIT_COLUMNS,
      closeModal,
      onBillClick,
      viewCarryOver,
      viewForfeit,
      handleCancelDetail,
      saveAddTurnover,
      handleAddTurnoverClose,
      handleAdd,
    };
  },
});

const INIT_COLUMNS = [
  {
    title: "账单编号",
    dataIndex: "bill_number",
    key: "bill_number",
    width: 200,
    fixed: "left",
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: 'cost_type_txt',
    width: 160,
  },
  {
    title: "计费周期",
    dataIndex: "billOn",
    key: 'billOn',
    width: 200,
  },
  {
    title: "账单金额",
    dataIndex: "bill_amount",
    key: 'bill_amount',
    width: 160,
  },
  {
    title: "滞纳金",
    dataIndex: "latefee_amount",
    key: "latefee_amount",
    width: 160,
    customRender: ({ text, record, index }) => {
      return text || "--";
    },
  },
  {
    title: "结转",
    dataIndex: "carry_over",
    key: "carry_over",
    width: 240,
  },
  {
    title: "实收/付金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: 180,
    customRender: ({ text, record, index }) => {
      return text ||  "--";
    },
  },
  {
    title: "罚没",
    dataIndex: "confiscations_amount",
    key: "confiscations_amount",
    width: 160,
  },
  {
    title: "应收/付日期",
    dataIndex: "receivable_payment_date",
    width: 180,
  },
  {
    title: "需收/付金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: 200,
    fixed: "right",
  },
]
</script>
<style lang="less" scoped>
:deep(.ant-statistic-title) {
  color: @primary-color;
}
:deep(.ant-statistic-content-value) {
  color: @primary-color;
  font-weight: bold;
}
.action-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>